navigator.getMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);

var id = new Date().getTime().toString();
var peer = new Peer(id, {host: location.hostname, port: 9000, path: '/ptpApi'});
var connectedPeers = {};

$(function() {
	// 监听视频相关事件
	peer.on('open', function () {
		$('#my-id').text(peer.id);
	});
	peer.on('call', function (call) {
		call.answer(window.localStream);
		showPartnerVideo(call);
	});
	peer.on('error', function (err) {
		alert(err.message);
	});

	// 监听文字消息事件
	peer.on('connection', function(conn) {
		connectData(conn);
	});

	$('#call').on('click', function() {
		var callID = $('#call-id').val();
		var call = peer.call(callID, window.localStream);
		showPartnerVideo(call);
	});
	$('#end-call').on('click', function() {
		window.existingCall && window.existingCall.close();
		$('#receiveMsg').empty();
	});
	// 先显示自己的视频
	showMyVideo();
});


function showMyVideo() {
	navigator.getMedia({audio: true, video: true}, function(stream){
		// Set your video displays
		$('#my-video').prop('src', URL.createObjectURL(stream));
		window.localStream = stream;
	}, function(){ $('#showMyVideo-error').show(); });
}

/**
 * show partner Video when trigger call
 * @param call
 */
function showPartnerVideo(call) {
	if (window.existingCall) {
		window.existingCall.close();
	}

	call.on('stream', function(stream) {
		$('#their-video').prop('src', URL.createObjectURL(stream));
	});

	call.on('close', function() {
		disConnectMedia();
	});

	window.existingCall = call;
	$('#their-id').text(call.peer);

	// Date connections
	if(!connectedPeers[call.peer]) {
		var conn = peer.connect(call.peer);
		conn.on('open', function() {
			connectData(conn);
			conn.send('Hi!');
		});
	}
	connectedPeers[call.peer] = 1;
}

/**
 * 断开视频连接
 */
function disConnectMedia() {
	$('#their-id').text('已断开连接');
	$('#receiveMsg').empty();
}

/**
 * 数据通道连接成功回调
 * @param conn
 */
function connectData(conn) {
	$('#msgContainer').show();
	conn.on('data', function(data) {
		$('#receiveMsg').append('<p style="color: green;">' + conn.peer + '：' + data + '</p>');
	});
	conn.on('close', function() {
		$('#receiveMsg').empty();
		delete connectedPeers[conn.peer];
	});
	conn.on('error', function(err) { alert(err)});
	$('#sendMsgBtn').off().on('click', function() {
		var msg = $('#msgToSend');
		conn && conn.send(msg.val());
		$('#receiveMsg').append('<p style="color: blue;">你：' + msg.val() + '</p>');
		msg.val('');
		msg.focus();
	});
	connectedPeers[conn.peer] = 1;
}